/**
 * <p>Package : org.tea.springdata.web.config</p>
 * <p>E-Mail : ztlyde@gmail.com</p>
 */
package org.tea.springdata.web.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * WEB应用初始化器
 * @author: John zhang
 * @version: 0.1
 */
public class WebIntializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
		// appContext.register(AppConfig.class);
		// appContext.refresh();
		servletContext.addListener(new ContextLoaderListener(appContext));
		
		AnnotationConfigWebApplicationContext appServlet = new AnnotationConfigWebApplicationContext();
		appServlet.register(WebConfig.class);
		// appServlet.setParent(appContext);
		// appServlet.refresh();
		
		FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter());
		characterEncodingFilter.setInitParameter("encoding", "UTF-8");
		characterEncodingFilter.setInitParameter("forceEncoding", "true");
		characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
		
		ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appServlet));
		registration.setLoadOnStartup(1);
		registration.addMapping("/*");
	}

}
